package com.hcbd.tdwt.ui.xingyu.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.base.BaseFragment;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.ConvertToBdMsgTool;
import com.hcbd.tdwt.base.GlobalParams;

import com.hcbd.tdwt.util.DateUtils;
import com.hcbd.tdwt.util.SharedPreferencesUtil;
import com.hcbd.tdwt.ui.xingyu.vo.Position;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.text.MessageFormat;
import java.util.Objects;

import static com.hcbd.tdwt.base.GlobalParams.sendBeidouMsgSignalEnable;
import static java.lang.Thread.sleep;


@SuppressLint("NonConstantResourceId")
@EFragment(R.layout.fragment_app_report_peace)
public class AppReportPeaceFragment extends BaseFragment {
    @ViewById(R.id.choose_contact_img)
    ImageView chooseContactImg;
    @ViewById
    EditText phoneNum,safeContentET;
    @ViewById
    RadioGroup safeRG;
    @ViewById
    RadioButton safeContent1,safeContent2,safeContent3,customizeRB;
    @ViewById
    Button sendBtn;
    @ViewById(R.id.position_info)
    TextView positionInfo;
    @ViewById
    LinearLayout bgLL;
    @ViewById(R.id.phone_left_tv)
    TextView  phoneLeftTv;
    @ViewById(R.id.situation_depict_tv)
    TextView situationDepictTv;

    Drawable lineColorDrawable;

    Drawable brightDrawable;
    SharedPreferencesUtil sp;
    @AfterViews
    protected void init() {
        setBgStyle();
        safeRG.setOnCheckedChangeListener((radioGroup, i) ->selectSafeContent() );
        brightDrawable=getResources().getDrawable(R.drawable.btn_light_blue_cilck_bg);
        sp=new SharedPreferencesUtil(getContext());
        safeContent1.setChecked(true);
        String lastNumber = sp.getAttribute(Constant.LAST_REPORT_PEACE_NUMBER);
        if (!TextUtils.isEmpty(lastNumber)) {
            phoneNum.setText(lastNumber);
        }
        autoRefresh();
        initGPS();
    }
    public void setBgStyle(){
        if(BdToolFactory.app_type==BdToolFactory.FU_DA_BG_TYPE||BdToolFactory.app_type==BdToolFactory.HLCT_BG_TYPE){
            positionInfo.setTextColor(getContext().getColor(R.color.black));
            safeContent1.setTextColor(getContext().getColor(R.color.black));
            safeContent2.setTextColor(getContext().getColor(R.color.black));
            safeContent3.setTextColor(getContext().getColor(R.color.black));
            customizeRB.setTextColor(getContext().getColor(R.color.black));
            positionInfo.setBackground(getContext().getDrawable(R.color.white));
            safeRG.setBackground(getContext().getDrawable(R.color.white));
            bgLL.setBackground(getContext().getDrawable(R.color.white));
            phoneLeftTv.setTextColor(getContext().getColor(R.color.black));
            phoneNum.setTextColor(getContext().getColor(R.color.black));
            lineColorDrawable=getResources().getDrawable(R.drawable.button_gray_bg);
            situationDepictTv.setBackground(getContext().getDrawable(R.color.white));
            safeContentET.setTextColor(getContext().getColor(R.color.black));
        }else{
            lineColorDrawable=getResources().getDrawable(R.drawable.bg_gray);
        }
    }
    @Click
    void sendBtn(){
        String phone = getTextStr(phoneNum);
        if (TextUtils.isEmpty(phone)) {
            toast("联系人号码不能为空");
            return;
        }
        String safeContent;
        RadioButton rb = getActivity().findViewById(safeRG.getCheckedRadioButtonId());
        String tag= rb.getTag().toString();
        if("customize".equals(tag)){
            safeContent=getTextStr(safeContentET);
            if("".equals(safeContent)){
                toast("请输入自定义的内容!");
                return;
            }
        }else{
            safeContent=rb.getText().toString();
        }
        Position position = new Position();
        position.setLongitude(BeidouBoxParams.gpsLonDou);
        position.setLatitude(BeidouBoxParams.gpsLatDou);
        position.setAltitude(GlobalParams.gpsAltitude);
        position.setTime(Long.parseLong(DateUtils.getTimeStamp()));
        if (BeidouBoxParams.isBoxConnectNormal) {
            sendBdMsg(phone,safeContent,position);
        } else {
            toast("请连接终端!");
        }


    }
    /**
     * 通过北斗网发送
     */
    private void sendBdMsg(String phone,String content, Position position) {
        int beidouSignal = BeidouBoxParams.getBdSignal();
        if (beidouSignal < sendBeidouMsgSignalEnable) {
            toast("信号不好，请移动终端位置");
            return;
        };
        String bdContent = ConvertToBdMsgTool.castUserMessageTo0x14(phone,content,position);
        BdToolFactory.getBdSendBase().sendMsg(GlobalParams.rdCentreNumber,2,2,bdContent);
        //最后一次发送的号码
        sp.addAttribute(Constant.LAST_REPORT_PEACE_NUMBER, phone);
        // 发送状态倒计时线程
        MainApp.getInstance().startNewSentWaitSecTimer();
        toast("发送成功");
    }
    public void selectSafeContent(){
        RadioButton rb = getActivity().findViewById(safeRG.getCheckedRadioButtonId());
        String tag= rb.getTag().toString();
        if("customize".equals(tag)){
            safeContentET.setVisibility(View.VISIBLE);
        }else{
            safeContentET.setVisibility(View.GONE);
        }
    }

    @Click(R.id.choose_contact_img)
    void chooseContactImg(){
        //选择联系人按钮,从手机通讯录添加联系人
        openContacts();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Constant.GET_MAIL_LIST_CONTACT_RESULT) {
                if (data != null) {
                    phoneNum.setText(getPhoneNum(data));
                }
            }
        }
    }

    /**
     * 刷新终端信息
     */
    private void refreshStatus() {
        if(sendBtn==null){
            return;
        }
        if(BeidouBoxParams.isBoxConnectNormal){
            int bdSignal = BeidouBoxParams.getBdSignal();
            if(BeidouBoxParams.sentWaitSec>0){
                sendBtn.setClickable(false);
                sendBtn.setText(MessageFormat.format("{0}S", BeidouBoxParams.sentWaitSec));
                sendBtn.setBackground(lineColorDrawable);
            }else if (bdSignal < sendBeidouMsgSignalEnable) {
                sendBtn.setClickable(false);
                sendBtn.setText("没信号");
                sendBtn.setBackground(lineColorDrawable);
            } else{
                sendBtn.setClickable(true);
                sendBtn.setText("发送");
                sendBtn.setBackground(brightDrawable);
            }
        }else{
            sendBtn.setClickable(false);
            sendBtn.setText("未连接！");
            sendBtn.setBackground(lineColorDrawable);
        }
        if ("".equals(BeidouBoxParams.gpsLongitude)|| "".equals(BeidouBoxParams.gpsLatitude)) {
            positionInfo.setText("未知");
        } else {
            positionInfo.setText(MessageFormat.format("经度:{0}纬度:{1}高度:{2}", BeidouBoxParams.gpsLongitude, BeidouBoxParams.gpsLatitude, BeidouBoxParams.gpsAltitude));
        }
    }


    private void initGPS() {
        LocationManager locationManager = (LocationManager) Objects.requireNonNull(this.getActivity()).getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            toast("请开启手机定位!");
        }else {
            MainApp.getInstance().initMap();
        }
    }
    /**
     * 刷新UI
     */
    @SuppressLint("HandlerLeak")
    private final Handler adapterHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                refreshStatus();
            }
        }
    };
    //是否刷新终端信息
    private boolean isRefreshing = false;
    /**
     * 自动刷新
     */
    private void autoRefresh() {
        if (isRefreshing) {
            return;
        }
        isRefreshing = true;
        new Thread(() -> {
            try {
                while (isRefreshing) {
                    Message msg = new Message();
                    msg.what = 1;
                    adapterHandler.sendMessage(msg);
                    sleep(1000);
                }
            } catch (Exception e) {
                Log.e("InfoMessage", e.toString());
            }
        }).start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isRefreshing = false;
        hideInputKeyBord();
    }
}
